package jym.tan.tmdb.method;

import java.net.URL;

import jym.tan.tmdb.TMDB;
import jym.tan.tmdb.bean.MovieSearchWrapper;
import jym.tan.tmdb.constant.TMDBConstants;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author Tanmoy
 * 
 */
public class SearchMovies extends BaseMethod {

	public SearchMovies(TMDB tmdb) {
		super(tmdb, TMDBConstants.SEARCH_MOVIES);
	}

	public MovieSearchWrapper search(String movieName, String year, int page, boolean allResults, String language, boolean includeAdult) throws Exception {
		String query = null;
		if (StringUtils.isNotBlank(year)) {
			query = new StringBuilder(movieName).append(" ").append(year).toString();
		} else {
			query = movieName;
		}

		URL searchURL = getUrl(query, TMDBConstants.BLANK, language, TMDBConstants.BLANK, page, includeAdult);
		MovieSearchWrapper wrapper = getTMDBObject(searchURL, MovieSearchWrapper.class);
		return allResults ? search(wrapper, query, language, includeAdult) : wrapper;
	}

	private MovieSearchWrapper search(MovieSearchWrapper wrapper, String query, String language, boolean includeAdult) throws Exception {
		if (wrapper.getTotalPages() == 1) {
			return wrapper;
		}

		for (int i = 2; i <= wrapper.getTotalPages(); i++) {
			URL searchURL = getUrl(query, TMDBConstants.BLANK, language, TMDBConstants.BLANK, i, includeAdult);
			MovieSearchWrapper movieSearchWrapper = getTMDBObject(searchURL, MovieSearchWrapper.class);
			wrapper.getResults().addAll(movieSearchWrapper.getResults());
		}

		return wrapper;
	}
}
